<template>
    <div id="app">
        <header>
            <h1><i class="fas fa-wave-square"></i> NFC读取器</h1>
            <p>使用NFC技术读取卡片数据</p>
            <div class="status-indicator">
                <div class="status-dot" :class="{ active: nfcActive }"></div>
                <span>{{ nfcActive ? '运行中' : '已停止' }}</span>
            </div>
        </header>

        <div class="main-content">
            <div style="text-align: center;">
                <div class="nfc-icon">
                    <i class="fas fa-rss"></i>
                </div>

                <!-- 添加状态提示 -->
                <div v-if="statusMessage" class="status-message">
                    {{ statusMessage }}
                </div>
            </div>

            <div class="control-section">
                <button class="btn btn-init" @click="initData" :disabled="initDataActive">
                    <i class="fas fa-stop"></i> 初始化名单
                </button>
                <button class="btn btn-start" @click="startNFC('signIn')" :disabled="nfcActive">
                    <i class="fas fa-play"></i> 签到
                </button>
                <button class="btn btn-stop" @click="startNFC('signOut')" :disabled="!nfcActive">
                    <i class="fas fa-stop"></i> 签退
                </button>
            </div>
        </div>

        <button class="btn-exit" @click="exitApp">
            <i class="fas fa-sign-out-alt"></i> 退出
        </button>

        <ConfirmDialog
                ref="confirmDialogRef"
                title="确认退出"
                message="确定要关闭 NFC 读取器吗？"
                @confirm="handleConfirm"
        />

        <!-- <footer>
            <p>Welink NFC读取器 &copy; 2025 | 基于华为We码平台</p>
        </footer> -->
        
    </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watchEffect } from 'vue';
import ConfirmDialog  from './ConfirmDialog.vue'

const confirmDialogRef = ref(null);

const param = ref(null);
const nfcActive = ref(false);
const statusMessage = ref(''); // 状态提示信息
let nfcCleanup = null; // 存储清理函数
let paramFetched = false; // 添加标志位
const initDataActive = ref(false);

const getQueryParams = () => {


    HWH5.app({

        // 当nfc读取卡片的时候该方法都会调用
        onShow(data) {
            
            if (!data || data.trim() === '') return // 防止重复获取

            param.value = data ? JSON.parse(data) : null;

        },
    }).catch(error => {
        alert("参数获取错误: " + error);
        param.value = null;
    });
};

// 导入参数人员数据到目标表
const initData = () => {

    if (initDataActive) return
    initDataActive = true

    // const _url = 'http://192.168.188.184:8422/api/weCode/signIn';
    const _url = 'http://192.168.188.199:8422/api/weCode/init';
    const _headers = {
        'Content-Type': 'application/json'
    };

    //测试数据
    // param.value = {
    //         table: "T_FORM_TB_1752941000931",
    //         field: 'INPUT_MDAFSM51, INPUT_MDAFSM52, INPUT_MDAFSM53'
    // }

    //真实数据
    const _params = {
        tableData: JSON.stringify(param.value)
    };

    // 1. 将参数对象转换为查询字符串
    const queryString = new URLSearchParams(_params).toString();

    //get方法
    const urlWithParams = _url + "?" + queryString

    HWH5.fetchInternet(urlWithParams, {
        method: 'get',
        headers: _headers
    })
    .then(res =>
        res.json())
    .then((response) => {
        if (response.data){

            statusMessage.value = response.data;

            if (nfcActive.value) return;

            nfcActive.value = true;

        } else{

            statusMessage.value = response.errorMessage;
        }
    })
    .catch(error => {
        console.error('数据初始化失败:', error);
        alert('数据初始化失败: ' + error.message);
    });
}

// 启动NFC持续监听
const startNFC = (signFlag) => {

    console.log('打卡标识 ->' + signFlag)

    if (nfcActive.value) return;

    nfcActive.value = true;

    statusMessage.value = '签到中...请将卡片靠近设备';

    // 使用watchEffect实现持续监听
    // nfcCleanup = watchEffect((onCleanup) => {
    //     if (!nfcActive.value) return;

    //     // 启动NFC模块
    //     HWH5.startNFC().catch(error => {
    //         statusMessage.value = 'NFC启动失败: ' + error;
    //         console.error("NFC启动失败:", error);
    //     });

    //     // 开始首次读取
    //     readCard();

    //     // 清理函数
    //     onCleanup(() => {
    //         HWH5.stopNFC().catch(console.error);
    //     });
    // });
};

// 定义读取函数
const readCard = async () => {
    try {
        const readData = await HWH5.readNFC();

        sendDataToBackend(readData);

        // 读取成功后继续监听下一张卡片
        if (nfcActive.value) {
            setTimeout(readCard, 1000); // 1秒后再次读取
        }
    } catch (error) {
        if (nfcActive.value) {
        // 安全获取错误信息
        const errorMsg = error?.message || String(error);

        // 忽略超时错误（卡片未靠近）
        if (!errorMsg.includes('超时')) {
            statusMessage.value = '监听中...请将卡片靠近设备';
            console.error("读取错误:", error);
        }
        setTimeout(readCard, 500);
        }
    }
};

// 停止NFC监听
const stopNFC = () => {
    if (!nfcActive.value) return;

    nfcActive.value = false;
    statusMessage.value = '已停止读卡';

    // 执行清理
    if (nfcCleanup) {
        nfcCleanup();
        nfcCleanup = null;
    }
};


// 发送数据到后端
const sendDataToBackend = (readData) => {

    // const _url = 'http://192.168.188.184:8422/api/weCode/signIn';
    const _url = 'http://192.168.188.199:8422/api/weCode/signIn';
    const _headers = {
        'Content-Type': 'application/json'
    };

    //测试数据
    // param.value = {
    //         table: "T_FORM_TB_1752941000931",
    //         field: 'INPUT_MDAFSM51, INPUT_MDAFSM52, INPUT_MDAFSM53'
    // }

    //真实数据
    const _params = {
        nfcData: JSON.stringify(readData),
        tableData: JSON.stringify(param.value)
    };

    // 1. 将参数对象转换为查询字符串
    const queryString = new URLSearchParams(_params).toString();

    //get方法
    const urlWithParams = _url + "?" + queryString

    HWH5.fetchInternet(urlWithParams, {
        method: 'get',
        headers: _headers
    })
    .then(res =>
        res.json())
    .then((response) => {
        if (response.data){

            statusMessage.value = response.data;
        } else{

            statusMessage.value = response.errorMessage;
        }
    })
    .catch(error => {
        console.error('发送数据失败:', error);
        alert('打卡失败: ' + error.message);
    });
};

const exitApp = () => {
    confirmDialogRef.value?.show();
};

const handleConfirm = () => {
  stopNFC();
  HWH5.close();
};

onMounted(() => {
    if (typeof HWH5 !== 'undefined') {
        console.log('WeLink NFC API 可用');
    } else {
        console.log('WeLink NFC API 不可用');
        statusMessage.value = '错误: NFC API不可用';
    }

    getQueryParams();
});

onUnmounted(() => {
    stopNFC(); // 组件卸载时停止监听
});
</script>

<style scoped>
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
}

body {
    background: linear-gradient(135deg, #1a2a6c, #b21f1f, #fdbb2d);
    min-height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 20px;
}

#app {
    width: 100%;
    max-width: 500px;
    background: rgba(255, 255, 255, 0.93);
    border-top-left-radius: 20px;
    border-top-right-radius: 20px;
    box-shadow: 0 15px 35px rgba(0, 0, 0, 0.3);
    overflow: hidden;
    height: 100vh; /* 100vh减去body的padding */
}

header {
    background: linear-gradient(to right, #0f4c81, #1a6fc4);
    color: white;
    padding: 25px 20px;
    text-align: center;
    position: relative;
}

header h1 {
    font-size: 1.8rem;
    margin-bottom: 5px;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 12px;
}

header p {
    opacity: 0.85;
    font-size: 0.95rem;
}

.status-indicator {
    position: absolute;
    top: 20px;
    right: 20px;
    display: flex;
    align-items: center;
    gap: 8px;
    background: rgba(255, 255, 255, 0.15);
    padding: 6px 12px;
    border-radius: 20px;
    font-size: 0.85rem;
}

.status-dot {
    width: 12px;
    height: 12px;
    border-radius: 50%;
    background: #ccc;
}

.status-dot.active {
    background: #4caf50;
    box-shadow: 0 0 10px #4caf50;
}

.nfc-icon {
    font-size: 2.5rem;
    margin: 25px auto;
    color: #1a6fc4;
    animation: pulse 2s infinite;
}

@keyframes pulse {
    0% { transform: scale(1); }
    50% { transform: scale(1.1); }
    100% { transform: scale(1); }
}

.main-content {
    padding: 25px 30px;
}

.control-section {
    display: flex;
    justify-content: center;
    gap: 20px;
    margin-bottom: 35px;
}

.btn {
    padding: 15px 25px;
    border: none;
    border-radius: 50px;
    font-size: 1.1rem;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    gap: 10px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.btn:disabled {
    opacity: 0.6;
    cursor: not-allowed;
}

.btn-start {
    background: linear-gradient(to right, #00c853, #64dd17);
    color: white;
}

.btn-stop {
    background: linear-gradient(to right, #ff5252, #ff867f);
    color: white;
}

.btn-init {
    background: linear-gradient(to right, rgb(0, 115, 255), #0d47a1);
    color: white;
}

.btn-simulate {
    background: linear-gradient(to right, #ff9800, #ffc107);
    color: white;
    margin: 0 auto;
    display: block;
}

.btn:hover:not(:disabled) {
    transform: translateY(-3px);
    box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
}

.btn:active:not(:disabled) {
    transform: translateY(0);
}

.card-data {
    background: #f5f9ff;
    border: 1px solid #d0e3ff;
    border-radius: 15px;
    padding: 20px;
    margin-top: 20px;
    min-height: 180px;
}

.card-data h3 {
    color: #0f4c81;
    margin-bottom: 15px;
    display: flex;
    align-items: center;
    gap: 10px;
}

.data-content {
    background: white;
    border-radius: 10px;
    padding: 15px;
    font-family: monospace;
    max-height: 250px;
    overflow-y: auto;
    box-shadow: inset 0 2px 5px rgba(0,0,0,0.05);
}

.data-item {
    margin-bottom: 8px;
    padding-bottom: 8px;
    border-bottom: 1px dashed #eee;
}

.data-item:last-child {
    border-bottom: none;
    margin-bottom: 0;
    padding-bottom: 0;
}

.key {
    font-weight: bold;
    color: #1a6fc4;
}

.value {
    color: #333;
    word-break: break-all;
}

.instructions {
    background: #fff8e1;
    border-left: 4px solid #ffc107;
    padding: 15px;
    border-radius: 0 10px 10px 0;
    margin-top: 25px;
    font-size: 0.9rem;
}

.instructions h4 {
    color: #ff9800;
    margin-bottom: 8px;
    display: flex;
    align-items: center;
    gap: 8px;
}

.instructions ul {
    padding-left: 20px;
}

.instructions li {
    margin-bottom: 6px;
}

footer {
    text-align: center;
    padding: 20px;
    color: #666;
    font-size: 0.85rem;
    border-top: 1px solid #eee;
}

@media (max-width: 480px) {
    .control-section {
        flex-direction: column;
        align-items: center;
        gap: 15px;
    }

    .btn {
        width: 100%;
        justify-content: center;
    }

    header h1 {
        font-size: 1.5rem;
    }

    .main-content {
        padding: 20px;
    }
    .status-message {
        font-size: 0.9rem;
        padding: 10px 15px;
    }
}

.btn-exit {
    position: fixed;
    right: 20px;
    bottom: 20px;
    background: rgb(241, 5, 5);
    border: 1px solid #ddd;
    border-radius: 50px;
    padding: 12px 20px;
    font-size: 0.95rem;
    cursor: pointer;
    color: rgb(255, 255, 255);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    display: flex;
    align-items: center;
    gap: 8px;
    transition: all 0.3s ease;
    z-index: 1000;
}

.status-message {
    margin: 20px auto;
    padding: 12px 20px;
    background-color: #e3f2fd;
    border-radius: 8px;
    max-width: 80%;
    font-size: 1rem;
    color: #0d47a1;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    transition: all 0.3s ease;
}

</style>
